package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageReturn;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.YddArticleDto;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.service.IYddArticleService;
import com.itheima.ydd.vo.YddArticleVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 03、内容管理（后台）/3.3、文章管理
 */
@RestController
@RequestMapping("/ydd_article")
public class YddArticleController {

    @Autowired
    private IYddArticleService yddArticleService;

    /**
     * 文章分页查询
     *
     * @param yddArticleDto
     * @return
     */
    @GetMapping("/list")
    public ResultData page(YddArticleDto yddArticleDto) {
        //分页查询拦截器
        Page<YddArticle> pageInfo = new Page(yddArticleDto.getPage(), yddArticleDto.getLimit());
        //条件构造器
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(StringUtils.isNotEmpty(yddArticleDto.getStart_time()), YddArticle::getCreateDate, yddArticleDto.getStart_time());
        queryWrapper.ge(StringUtils.isNotEmpty(yddArticleDto.getEnd_time()), YddArticle::getCreateDate, yddArticleDto.getEnd_time());
        queryWrapper.like(StringUtils.isNotEmpty(yddArticleDto.getTitle()), YddArticle::getTitle, yddArticleDto.getTitle());
        queryWrapper.eq(yddArticleDto.getCateid() != null, YddArticle::getCateid, yddArticleDto.getCateid());
        //查询
        Page<YddArticleVo> res = yddArticleService.pageByCondition(pageInfo, queryWrapper);
        //返回数据封装
        PageReturn<YddArticleVo> change = PageReturn.change(res);
        //返回数据
        return ResultData.ok("", change);
    }

    /**
     * 文章删除(数据库真实删除)
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(int id) {
        yddArticleService.removeById(id);
        return ResultData.ok("删除成功", null);
    }

    /**
     * 文章添加
     *
     * @param yddArticle
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddArticle yddArticle) {
        yddArticleService.save(yddArticle);
        return ResultData.ok("添加文章成功", null);
    }

    /**
     * 文章详情(用于后台内容回显)
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(int id) {
        YddArticle yddArticle = yddArticleService.getById(id);
        return ResultData.ok("", yddArticle);
    }

    /**
     * 文章修改
     *
     * @param yddArticle
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddArticle yddArticle) {
        yddArticleService.updateById(yddArticle);
        return ResultData.ok("修改成功", null);
    }

}
